


package com.eric.config.spi;

import com.google.common.base.Strings;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.spi.database.metadata.DataSourceMetaData;
import org.apache.shardingsphere.underlying.common.database.metadata.UnrecognizedDatabaseURLException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 扩展达梦数据库元数据
 */
@Getter
@Slf4j
public class DMDataSourceMetaData implements DataSourceMetaData {
    private static final int DEFAULT_PORT = 5236;

    private final String hostName;

    private final int port;

    private final String catalog;

    private final String schema;

//    private final Pattern pattern = Pattern.compile("jdbc:dm://([\\w\\-.]+):?([0-9]*)", Pattern.CASE_INSENSITIVE);
    /**
     * 匹配达梦url的正则表达式，以来解析主机、端口、用户名和密码等
     */
    private Pattern pattern = Pattern.compile("jdbc:dm://([\\w\\-\\.]+):?([0-9]*)(/?)([\\w\\-]*)", Pattern.CASE_INSENSITIVE);


    public DMDataSourceMetaData(final String url, final String username) {
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find()) {
            throw new UnrecognizedDatabaseURLException(url, this.pattern.pattern());
        }
        hostName = matcher.group(1);
        port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2));
//        catalog = username;
//        schema = username;
        catalog = matcher.group(3);
        schema = username;

        System.out.println("hostName: " + this.hostName + " port: " + this.port + " url: " + url + " username: " + username + " catalog: " + this.catalog + " schema: " + this.schema);
    }

}
